# _*_coding     : UTF_8_*_
# Author        :Jie Shen
# CreatTime     :2021/12/15 14:09
import re

import pandas as pd
from matplotlib import pyplot as plt


def get_filename(year):
    _month_filename = [str(year) + str(i).zfill(2) + ".csv" for i in range(1, 13)]
    return _month_filename


def get_wind_class(year):
    """
    遍历2021年的每一天，统计有哪几种风
    2021年的风向: ['南风', '东风', '北风', '西北风', '西风', '西南风', '东南风', '东北风']
    :return: 返回不同风向名字列表
    """

    _month_filename = get_filename(str(year))
    _wind_class = []
    for m in _month_filename:
        _csv = pd.read_csv("csv/" + str(year) + "/" + m)
        # 某月每一天的风向
        wind_ = _csv['风向']
        for w in wind_:
            w_ = w.split()[0]  # 不需要风向的级数
            if w_ in _wind_class:
                continue
            else:
                _wind_class.append(w_)
    return _wind_class


def init_wind_dict(year):
    """
    # 风的类别: ['南风', '东风', '北风', '西北风', '西风', '西南风', '东南风', '东北风']

    返回值示例:
    {
        '南风': {
            '01': ['2021-01-01', '2021-01-13', '2021-01-18', '2021-01-31'],
            '02': ['2021-02-06'], '03': ['2021-03-23', '2021-03-24', '2021-03-28']
            ...
            }
        '东风': {
            '01': ['2021-01-02', '2021-01-20', '2021-01-24'],
            '02': ['2021-02-02', '2021-02-10', '2021-02-23'],
            ...
            }
        ...
    }
    :return:
    """
    _wind_class = get_wind_class(year)
    wind_dict = {}

    for w in _wind_class:
        wind_dict[w] = {}
        for i in range(1, 13):
            wind_dict[w][str(i).zfill(2)] = []

    _month_filename = get_filename(str(year))
    _wind_class = []
    # 年
    for m in _month_filename:

        # 某月的数据
        _csv = pd.read_csv("csv/" + str(year) + "/" + m)
        # 某天的风向
        wind_month_ = _csv['风向']
        for w in range(len(wind_month_)):
            # w.split()[0] 某个风向
            wind_direction = _csv['风向'][w].split()[0]

            # "2021-08-18"
            wind_date = _csv.loc[w, '日期'].split()[0]
            # 属于第几月的风
            _m = wind_date.split('-')[1]

            wind_dict[wind_direction][_m].append(wind_date)
    return wind_dict


def wind_line(year):
    """
    绘制风向的折线图
    2021年的风向: ['南风', '东风', '北风', '西北风', '西风', '西南风', '东南风', '东北风']

    :return:
    """

    plt.figure(figsize=(20, 8), dpi=80)
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

    wind_dict = init_wind_dict(year)
    # 设置图片大小,dpi分辨率，更清晰
    x = [i for i in range(1, 13)][:-1:]
    wind_direction = wind_dict.keys()

    for w in wind_direction:
        y_ = [len(n[1]) for n in wind_dict[w].items()][:-1:]

        plt.plot(x, y_, label=w, linewidth=3)
    plt.xlabel("月份")
    plt.ylabel("次数")
    plt.title("2021武汉每月风向次数统计图")
    plt.legend()
    plt.grid(alpha=0.5)
    # 展示图形
    plt.show()
    plt.savefig("img/全年风向次数图.png")


def temperature_line(year):
    plt.figure(figsize=(20, 8), dpi=80)
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
    temperature_dict = init_temperature(year)
    x_ = temperature_dict.keys()
    y_h = [int(temperature_dict[i][0][:-1:]) for i in x_]
    y_l = [int(temperature_dict[i][1][:-1:]) for i in x_]
    plt.plot(x_, y_h, label='最高气温', c='orange')
    plt.plot(x_, y_l, label='最低气温')
    plt.xticks(list(x_)[::15])
    plt.xlabel('日期')
    plt.ylabel('气温/℃')
    plt.title('2021武汉温度折线图')
    plt.legend()
    plt.grid(alpha=0.5)
    plt.show()
    plt.savefig('img/2021武汉温度折线图.png')
    # y_h = temperature_dict


def init_temperature(year):
    """
    返回值示例:
    {
        '01.01': ('8℃', '-5℃'),
        '01.02': ('10℃', '-1℃'),
        '01.03': ('8℃', '-2℃')
        ...
    }
    :param year:
    :return:
    """
    csv_name = get_filename(year)
    temperature_dict = {}
    for c in csv_name:
        path = "csv/{year}/{filename}".format(year=year, filename=c)
        _pd = pd.read_csv(path)

        highest_temperature = _pd['最高气温']
        lowest_temperature = _pd['最低气温']
        Min_len = min(len(highest_temperature), len(lowest_temperature))
        for i in range(Min_len):
            # date_ = _pd.loc[i, '日期'].split()[:-1:]
            x_ = '.'.join(re.split('[ -]', _pd.loc[i, '日期'].strip())[:-1:][1::])
            temperature_tuple = (_pd['最高气温'][i], _pd['最低气温'][i])
            temperature_dict[x_] = temperature_tuple
    return temperature_dict
    # 2020-11-01 星期日 -> 11.01

    # 19℃,14℃ -> 19,14


def init_weather(year):
    csv_name = get_filename(year)
    weather_list = []
    for c in csv_name:
        path = "csv/{year}/{filename}".format(year=year, filename=c)
        _pd = pd.read_csv(path)
        _weather = _pd['天气']
        for w in _weather:
            if w not in weather_list:
                weather_list.append(w)
    return weather_list


def weather_pie(year):
    """
    天气饼状图绘制

    weather_dict示例:
    {
        '晴': ['2021-01-01', '2021-01-03', '2021-01-05', ...],
        '多云': ['2021-01-02', '2021-01-04', '2021-01-06', ...],
        ...
    }
    :return:
    """
    plt.figure(figsize=(16,8))
    # 将横、纵坐标轴标准化处理，保证饼图是一个正圆，否则为椭圆
    plt.axis('equal')
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

    weather_list = init_weather(year)
    csv_name = get_filename(year)
    weather_dict = {}
    for w in weather_list:
        weather_dict[w] = []

    for c in csv_name:
        path = "csv/{year}/{filename}".format(year=year, filename=c)
        _pd = pd.read_csv(path)
        _weather = _pd['天气']
        for i in range(len(_weather)):
            weather_dict[_pd['天气'][i]].append(_pd.loc[i, '日期'].strip().split()[:-1:][0])
    label_ = [i for i in weather_dict.keys()]
    data_ = [len(weather_dict[i]) for i in label_]
    print(data_)
    print(label_)
    plt.pie(x=data_, labels=label_)
    plt.title("2021武汉天气饼状图")
    plt.legend()
    plt.show()
    plt.savefig('img/weather.png')
    return weather_dict


if __name__ == '__main__':
    weather_pie(2021)
    # temperature_line(2021)
    # wind_line(2021)
